package sk.atletis.atletika;

import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class ArticlesDetailFragment extends Fragment 
{
	public static final String ARTICLE_ID = "articleId";
	
	private long id;
	public TextView tvTitleBar, tvTitle, tvDate, tvPerex, tvText;
	public ImageView ivImage;

    public ArticlesDetailFragment() { }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
    {
        View root = inflater.inflate(R.layout.fragment_articles_detail, container, false);

        this.tvTitle = (TextView) root.findViewById(R.id.tvTitle);
		this.tvDate = (TextView) root.findViewById(R.id.tvDate);
		this.tvPerex = (TextView) root.findViewById(R.id.tvPerex);
		this.tvText = (TextView) root.findViewById(R.id.tvText);
		this.ivImage = (ImageView) root.findViewById(R.id.ivMain);
		     
		try
		{
			Bundle args = this.getArguments();
			this.id = args.getLong(ARTICLE_ID);
			
			Cursor c = this.getActivity().getContentResolver().query(ArticlesContract.CONTENT_URI_ARTICLES, 
					ArticlesContract.PROJECTION_COMPLETE, 
					ArticlesContract._ID + " = ?",
					new String[] {String.valueOf(this.id)}, 
					ArticlesContract.SORT_DEFAULT);
			
			if (c.moveToFirst()) 
			{
				this.getActivity().setTitle(c.getString(c.getColumnIndex(ArticlesContract.TITLE)));
				
				this.tvTitle.setText(c.getString(c.getColumnIndex(ArticlesContract.TITLE)));
				this.tvPerex.setText(c.getString(c.getColumnIndex(ArticlesContract.PEREX)));
				this.tvText.setText(Html.fromHtml(c.getString(c.getColumnIndex(ArticlesContract.ARTICLETEXT))));
				
				String sDate = DateHelper.DbString2String(c.getString(c.getColumnIndex(ArticlesContract.DATE)));
				if (sDate == "")
					this.tvDate.setText(c.getString(c.getColumnIndex(ArticlesContract.EDITOR)));
				else
					this.tvDate.setText(c.getString(c.getColumnIndex(ArticlesContract.EDITOR)) + " - " + sDate);
				
				if (c.getBlob(c.getColumnIndex(ArticlesContract.IMAGEFILE)) != null)
				{
					byte[] blob = c.getBlob(c.getColumnIndex(ArticlesContract.IMAGEFILE));
					Bitmap img = BitmapFactory.decodeByteArray(blob, 0, blob.length);
					ivImage.setImageBitmap(img);
				}
			}
		}
		catch (Exception e)
		{
			Toast.makeText(this.getActivity(), e.toString(), Toast.LENGTH_LONG).show();
		}
		
		return root;
    }
}
